import React, { useState, useEffect } from 'react';
import { Toast } from 'antd-mobile';
import { useNavigate, useLocation } from 'react-router-dom';
import axiosInstance from '../api/axios';
import { getEndpoint, getUserId, getEmail } from '../utils/storage';
import { endpoints } from '../api/endpoints';

const PAGE_SIZE = 10;

const Backpack = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const storeId = location.state?.storeId;
  
  const [activeKey, setActiveKey] = useState('shop');
  // 积分商城
  const [shopList, setShopList] = useState([]);
  const [shopPage, setShopPage] = useState(1);
  const [shopTotal, setShopTotal] = useState(-1);
  const [shopLoading, setShopLoading] = useState(false);
  const [shopDetail, setShopDetail] = useState(null);
  // 我的背包
  const [bagList, setBagList] = useState([]);
  const [bagLoading, setBagLoading] = useState(false);
  const [bagCode, setBagCode] = useState(null);
  const [videoScore, setVideoScore] = useState(null);
  // 兑换状态
  const [redeeming, setRedeeming] = useState(false);

  // tab切换时加载数据
  useEffect(() => {
    if (activeKey === 'shop') {
      fetchBagList();
      fetchShopList(1);
    } else {
      fetchBagList();
    }
    // eslint-disable-next-line
  }, [activeKey]);

  // 获取积分商城数据
  const fetchShopList = async (page = 1) => {
    setShopLoading(true);
    try {
      const params = {
        page,
        perPage: PAGE_SIZE,
        sort: '-created',
        skipTotal: 1,
        filter: 'status=true'
      };
      
      // 如果有商户ID，添加到过滤条件
      if (storeId) {
        params.filter = `status=true && belongto_store.id="${storeId}"`;
      }
      
      const res = await axiosInstance.get(endpoints.getMallList, { params });
      setShopList(res.data.items);
      setShopPage(page);
      setShopTotal(res.data.totalItems);
    } catch (e) {
      // Toast.show({ content: '加载失败', position: 'center' });
    } finally {
      setShopLoading(false);
    }
  };

  // 获取我的背包数据
  const fetchBagList = async () => {
    setBagLoading(true);
    try {
      const requestData = {};
      
      // 如果有商户ID，添加到请求数据
      if (storeId) {
        requestData.store_id = storeId;
      }
      
      const res = await axiosInstance.post(endpoints.getBagList, requestData);
      setBagList(res.data.data || []);
      if (typeof res.data.video_score !== 'undefined') {
        setVideoScore(res.data.video_score);
      }
    } catch (e) {
      // Toast.show({ content: '加载失败', position: 'center' });
    } finally {
      setBagLoading(false);
    }
  };

  // 兑换商品
  const handleRedeem = async (productId) => {
    setRedeeming(true);
    try {
      const requestData = {
        product_id: productId
      };
      
      // 如果有商户ID，添加到请求数据
      if (storeId) {
        requestData.store_id = storeId;
      }
      
      const res = await axiosInstance.post(endpoints.redeemProduct, requestData);
      
      // 检查响应中是否包含错误信息
      if (res.data.error) {
        // 有错误信息，显示错误
        let message = res.data.error;
        if (res.data.time !== undefined) {
          message += `，还需等待 ${res.data.time} 小时`;
        }
        Toast.show({ content: message, position: 'center' });
      } else {
        // 成功兑换
        Toast.show({ content: res.data.msg || '兑换成功', position: 'center' });

  
        // 插入兑换记录
        if (res.data.data) {
          const exchangeData = res.data.data;
          const userId = getUserId();
          const userEmail = getEmail();
          
          // 获取当前商品信息
          const currentProduct = shopList.find(item => item.id === productId);
          
          if (userId && userEmail && currentProduct) {
            try {
   
              const recordData = {
                product_id: exchangeData.product_id,
                product_name: exchangeData.product_name,
                points_spent: currentProduct.points_score,
                quantity: 1,
                exchange_time: exchangeData.exchange_time,
                valid_time: exchangeData.valid_time,
                user_id: userId,
                user_email: userEmail,
                product_pic_url: exchangeData.product_pic_url
              };
              
              // 如果有商户ID，添加到记录数据
              if (storeId) {
                recordData.store_id = storeId;
              }
              
              await axiosInstance.post(endpoints.insertExchangeRecord, recordData);
            } catch (recordError) {
              console.error('插入兑换记录失败:', recordError);
              // 不影响主流程，只记录错误
            }
          }
        }
        
        // 兑换成功后刷新数据
        fetchBagList();
        fetchShopList(shopPage);
        
        // 关闭详情弹窗
        handleCloseDetail();
      }
      
    } catch (error) {
      console.error('兑换商品失败:', error);
      // 处理网络错误或其他异常
      if (error.response && error.response.data) {
        const { msg, error: errorMsg, time } = error.response.data;
        let message = msg || errorMsg || '兑换失败';
        
        // 如果有剩余时间信息，添加到消息中
        if (time !== undefined) {
          message += `，还需等待 ${time} 小时`;
        }
        
        Toast.show({ content: message, position: 'center' });
      } else {
        Toast.show({ content: '兑换失败，请稍后重试', position: 'center' });
      }
    } finally {
      setRedeeming(false);
    }
  };

  // 查看详情弹窗
  const handleShowDetail = (item) => {
    setShopDetail(item);
  };

  // 关闭详情弹窗
  const handleCloseDetail = () => {
    setShopDetail(null);
  };

  // 查看核销码弹窗
  const handleShowCode = (item) => {
    setBagCode(item);
  };

  // 关闭核销码弹窗
  const handleCloseCode = () => {
    setBagCode(null);
  };

  // 分页导航
  const totalPages = shopTotal > 0 ? Math.ceil(shopTotal / PAGE_SIZE) : 1;
  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages || page === shopPage) return;
    fetchShopList(page);
  };

  // 小巧加载动画
  const Loading = () => (
    <div style={{ textAlign: 'center', margin: '24px 0', fontSize: 12, color: '#888' }}>
      <span className="loader" style={{ display: 'inline-block', width: 16, height: 16, border: '2px solid #1677ff', borderTop: '2px solid transparent', borderRadius: '50%', animation: 'spin 1s linear infinite', marginRight: 8 }} />加载中...
      <style>{`@keyframes spin { 100% { transform: rotate(360deg); } }`}</style>
    </div>
  );

  // 分页导航条
  const Pagination = () => (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, margin: '12px 0' }}>
      <button className="page-btn" style={pageBtnStyle} disabled={shopPage === 1} onClick={() => handlePageChange(shopPage - 1)}>上一页</button>
      {Array.from({ length: totalPages }).map((_, idx) => (
        <button
          key={idx + 1}
          className="page-btn"
          style={{ ...pageBtnStyle, fontWeight: shopPage === idx + 1 ? 600 : 400, background: shopPage === idx + 1 ? '#e6f4ff' : '#fff' }}
          onClick={() => handlePageChange(idx + 1)}
        >
          {idx + 1}
        </button>
      ))}
      <button className="page-btn" style={pageBtnStyle} disabled={shopPage === totalPages} onClick={() => handlePageChange(shopPage + 1)}>下一页</button>
    </div>
  );

  // 小巧按钮样式
  const pageBtnStyle = {
    border: '1px solid #eee',
    borderRadius: 4,
    padding: '2px 8px',
    fontSize: 13,
    background: '#fff',
    color: '#1677ff',
    cursor: 'pointer',
    minWidth: 32,
    margin: 0,
    outline: 'none',
    transition: 'background 0.2s',
    boxShadow: '0 1px 2px rgba(0,0,0,0.02)'
  };

  // 小巧卡片样式
  const cardStyle = {
    display: 'flex',
    alignItems: 'center',
    background: '#fff',
    borderRadius: 8,
    boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
    padding: 10,
    marginBottom: 10,
    gap: 10,
    fontSize: 14
  };
  const imgStyle = { width: 48, height: 48, borderRadius: 6, objectFit: 'cover', background: '#f5f5f5' };
  const btnStyle = { border: 'none', background: '#1677ff', color: '#fff', borderRadius: 4, padding: '2px 10px', fontSize: 13, cursor: 'pointer', marginLeft: 8 };

  return (
    <div className="min-h-screen flex flex-col bg-gray-50" style={{ height: '100vh', background: '#f7f8fa' }}>
      <div style={{ background: '#fff', borderBottom: '1px solid #eee', padding: '10px 0', textAlign: 'center', fontWeight: 600, fontSize: 18, position: 'sticky', top: 0, zIndex: 10 }}>
        <button onClick={() => navigate(-1)} style={{ position: 'absolute', left: 12, top: 10, background: 'none', border: 'none', color: '#1677ff', fontSize: 16, cursor: 'pointer' }}>←</button>
        我的背包
        {videoScore !== null && (
          <span style={{ position: 'absolute', right: 16, top: 10, color: '#faad14', fontSize: 13 }}>
            积分:{videoScore}
          </span>
        )}
      </div>
      {/* 自定义 Tabs */}
      <div style={{ display: 'flex', background: '#fff',borderBottom: '2px solid #eee' }}>
        <button
          style={{
            flex: 1,
            padding: '12px 0',
            fontSize: 16,
            fontWeight: 600,
            color: activeKey === 'shop' ? '#1677ff' : '#888',
            background: 'none',
            border: 'none',
            borderBottom: activeKey === 'shop' ? '2px solid #1677ff' : '2px solid transparent',
            cursor: 'pointer',
            transition: 'color 0.2s, border-bottom 0.2s',
          }}
          onClick={() => setActiveKey('shop')}
        >
          积分商城
        </button>
        <button
          style={{
            flex: 1,
            padding: '12px 0',
            fontSize: 16,
            fontWeight: 600,
            color: activeKey === 'bag' ? '#1677ff' : '#888',
            background: 'none',
            border: 'none',
            borderBottom: activeKey === 'bag' ? '2px solid #1677ff' : '2px solid transparent',
            cursor: 'pointer',
            transition: 'color 0.2s, border-bottom 0.2s',
          }}
          onClick={() => setActiveKey('bag')}
        >
          我的背包
        </button>
      </div>
      {/* Tab 内容 */}
      {activeKey === 'shop' && (
        <div style={{ padding: '12px 8px' }}>
          {shopLoading && shopList.length === 0 ? (
            <Loading />
          ) : shopList.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#bbb', fontSize: 14, margin: '40px 0' }}>暂无商品</div>
          ) : (
            <div>
              {shopList.map(item => (
                <div key={item.id} style={cardStyle}>
                  <img src={`${getEndpoint()}/api/files/${item.collectionId}/${item.id}/${item.image_file}`} alt="商品" style={imgStyle} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500 }}>{item.product_name}</div>
                    <div style={{ color: '#888', fontSize: 12 }}>{item.product_desc}</div>
                    <div style={{ color: '#faad14', fontSize: 13 }}>积分：{item.points_score}</div>
                    <div style={{ color: '#aaa', fontSize: 12 }}>库存：{item.stock}</div>
                  </div>
                  <button 
                    style={{ 
                      ...btnStyle, 
                      background: item.stock === 0 ? '#ccc' : '#1677ff',
                      cursor: item.stock === 0 ? 'not-allowed' : 'pointer'
                    }} 
                    onClick={() => item.stock > 0 && handleShowDetail(item)}
                    disabled={item.stock === 0}
                  >
                    {item.stock === 0 ? '无库存' : '详情'}
                  </button>
                </div>
              ))}
              <Pagination />
            </div>
          )}
        </div>
      )}
      {/* 商品详情弹窗 */}
      {activeKey === 'shop' && shopDetail && (
        <div style={{ position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: 'rgba(0,0,0,0.25)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={handleCloseDetail}>
          <div style={{ background: '#fff', borderRadius: 10, padding: 24, minWidth: 260, maxWidth: 320, boxShadow: '0 2px 16px rgba(0,0,0,0.08)', textAlign: 'center', position: 'relative' }} onClick={e => e.stopPropagation()}>
            <img src={ `${getEndpoint()}/api/files/${shopDetail.collectionId}/${shopDetail.id}/${shopDetail.image_file}`} alt="商品" style={{ width: 100, height: 100, borderRadius: 10, marginBottom: 12, objectFit: 'cover' }} />
            <div style={{ fontWeight: 600, fontSize: 18 }}>{shopDetail?.product_name}</div>
            <div style={{ color: '#888', margin: '8px 0' }}>{shopDetail?.product_desc}</div>
            <div style={{ color: '#faad14', fontSize: 15 }}>
              积分：{shopDetail?.points_score}
              {shopDetail?.sold_strategy === "只需积分" ? " (只需积分)" : ` +${shopDetail?.sold_strategy_num} 元`}
            </div>
            <div style={{ color: '#aaa', fontSize: 12, margin: '8px 0' }}>库存：{shopDetail?.stock}</div>
            <div style={{ color: '#aaa', fontSize: 12 }}>已售：{shopDetail?.sold}</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button 
                style={{ 
                  ...btnStyle, 
                  flex: 1, 
                  background: redeeming ? '#ccc' : '#52c41a',
                  cursor: redeeming ? 'not-allowed' : 'pointer'
                }} 
                onClick={() => handleRedeem(shopDetail.id)}
                disabled={redeeming}
              >
                {redeeming ? '兑换中...' : '兑换'}
              </button>
              <button style={{ ...btnStyle, flex: 1, background: '#888' }} onClick={handleCloseDetail}>关闭</button>
            </div>
          </div>
        </div>
      )}
      {activeKey === 'bag' && (
        <div style={{ padding: '12px 8px' }}>
          {bagLoading ? (
            <Loading />
          ) : bagList.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#bbb', fontSize: 14, margin: '40px 0' }}>暂无背包物品</div>
          ) : (
            <div>
              {bagList.map(item => (
                <div key={item.code} style={cardStyle}>
                  <img src={`${getEndpoint()}/api/files/points_product/${item.product_id}/${item.product_pic_name}`} alt="物品" style={imgStyle} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500 }}>{item.product_name}</div>
                    <div style={{ color: '#888', fontSize: 12 }}>兑换时间：{item.exchange_time}</div>
                    {/* 有效期 */}
                    <div style={{ color: '#888', fontSize: 12 }}>有效期：{item.valid_time}</div>
                  </div>
                  <button style={btnStyle} onClick={() => handleShowCode(item)}>核销码</button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
      {/* 核销码弹窗 */}
      {activeKey === 'bag' && bagCode && (
        <div style={{ position: 'fixed', left: 0, top: 0, width: '100vw', height: '100vh', background: 'rgba(0,0,0,0.25)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={handleCloseCode}>
          <div style={{ background: '#fff', borderRadius: 10, padding: 24, minWidth: 240, maxWidth: 320, boxShadow: '0 2px 16px rgba(0,0,0,0.08)', textAlign: 'center', position: 'relative' }} onClick={e => e.stopPropagation()}>
            <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 8 }}>{bagCode?.product_name}</div>
            <img src={`${getEndpoint()}/api/files/points_product/${bagCode?.product_id}/${bagCode?.product_pic_name}`} alt="物品" style={{ width: 80, height: 80, borderRadius: 10, marginBottom: 12, objectFit: 'cover' }} />
            <div style={{ fontSize: 16, color: '#1677ff', margin: '8px 0' }}>核销码：{bagCode?.code}</div>
            <div style={{ color: '#888', fontSize: 12 }}>兑换时间：{bagCode?.exchange_time}</div>
            <button style={{ ...btnStyle, marginTop: 16, width: '80%' }} onClick={handleCloseCode}>关闭</button>
          </div>
        </div>
      )}
    </div>
  );
};

export default Backpack; 